package Demo1;

class ListNode{
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
        this.next =null;
    }
}
public class T29 {

    public static ListNode mergeTwoLists(ListNode node1, ListNode node2){
//        如果其中一个为 0 则直接返回另一个
        if (node1 == null) return node2;
        if (node2 == null) return node1;

        ListNode head ;//头节点
//        确定头节点
        if (node1.val > node2.val){
            head = node2;
            node2 = node2.next;
        }else {
            head = node1;
            node1 = node1.next;
        }
//        开始插入节点
        ListNode cur = head;
        while(node1 != null && node2 != null){
            if (node1.val > node2.val){
                cur.next = node2;
                node2 = node2.next;
            }else {
                cur.next = node1;
                node1 = node1.next;
            }
            cur = cur.next;
        }
        cur.next = (node1 == null) ? node2: node1;
        return head;
    }
    public static void main(String[] args) {
//       两个链表合并成一个新链表
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);

        ListNode merged = mergeTwoLists(l1, l2);
        while (merged != null) {
            System.out.print(merged.val + " -> ");
            merged = merged.next;
        }
        System.out.println("null");
    }
}
